﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Text.RegularExpressions;

namespace FTPLib
{
    public class FTPCore
    {
        private string FtpServerIP;
        private string FtpUserId;
        private string FtpPassword;

        public string FTPSERVERIP
        {
            get { return FtpServerIP; }
            set { FtpServerIP = value; }
        }
        public string FTPUSERID
        {
            get { return FtpUserId; }
            set { FtpUserId = value; }
        }
        public string FTPPASSWORD
        {
            get { return FtpPassword; }
            set { FtpPassword = value; }
        }

        public FTPCore()
        {
        }

        public FTPCore(string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            FtpServerIP = ftpServerIP;
            FtpUserId = ftpUserID;
            FtpPassword = ftpPassword;
        }

        public void Download(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                //filePath = <<The full path where the file is to be created.>>, 
                //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
                

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSERVERIP + "/" + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FTPUSERID, FTPPASSWORD);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                
                response.Close();
                //FileInfo info = new FileInfo(fileName);
                //StreamReader reader = new StreamReader(outputStream);
               

             
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
            
        }

        public void ReadFile(string filePath, string fileName)
        {
            FtpWebRequest tmpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSERVERIP + "/" + fileName));

            tmpReq.Credentials = new System.Net.NetworkCredential(FTPUSERID, FTPPASSWORD);
           

                //GET THE FTP RESPONSE  
            try
            {
                tmpReq.UsePassive = true;
                tmpReq.UseBinary = true;
                tmpReq.KeepAlive = true;


                using (WebResponse tmpRes = tmpReq.GetResponse())
                {
                    //GET THE STREAM TO READ THE RESPONSE FROM  
                    using (Stream tmpStream = tmpRes.GetResponseStream())
                    {
                        //CREATE A TXT READER (COULD BE BINARY OR ANY OTHER TYPE YOU NEED)  
                        using (StreamReader tmpReader = new System.IO.StreamReader(tmpStream))
                        {
                            //STORE THE FILE CONTENTS INTO A STRING  
                            //string fileContents = tmpReader.ReadToEnd();
                            //DO SOMETHING WITH SAID FILE CONTENTS
                            // tmpStream.Close();
                            tmpRes.Close();
                            //tmpRes.Close();
                            //tmpStream.Close();
                            string line;
                            FileStream xml_out = new FileStream(@"C:\Users\DevArea\Desktop\nice book\testmyxml.xml", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                            while ((line=tmpReader.ReadLine())!=null)
                            {

                                Regex linePattern = new Regex(@"^(?<FileNo>\d{5})(?<CreationDate>\d{8})(?<DeliveryDate>\d{8})");
                                
                                XmlWriterSettings settings = new XmlWriterSettings();
                                settings.Indent = true;
                                using (XmlWriter writer = XmlWriter.Create(xml_out, settings))
                                {
                                    writer.WriteStartDocument();
                                    writer.WriteStartElement("Root");

                                    {

                                        {
                                            Match match = linePattern.Match(line);
                                            if (match.Success)
                                            {
                                                writer.WriteStartElement("Line");
                                                writer.WriteElementString("FileNo", match.Groups["FileNo"].Value);
                                                writer.WriteElementString("CreationDate", match.Groups["CreationDate"].Value);
                                                writer.WriteElementString("DeliveryDate", match.Groups["DeliveryDate"].Value);
                                                writer.WriteEndElement();
                                            }
                                        }

                                    }
                                    writer.WriteEndElement();
                                    writer.WriteEndDocument();
                                }


                                
                                //tmpReader.Close();
                                
                                tmpStream.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSERVERIP + "/" + filename));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(FTPUSERID, FTPPASSWORD);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return fileSize;
        }

        public void UploadTo(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + FTPSERVERIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSERVERIP + "/" + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(FTPUSERID, FTPPASSWORD);

            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();
            
            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                
                MessageBox.Show("Download Complete, status {0}", response.StatusDescription);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Upload Error");
            }
        }

        public bool TestConnection(string srvIP,string user,string pass)
        {
            

            try
            {
                FtpWebRequest requestDir = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FTPSERVERIP + "/"));
                requestDir.Method = WebRequestMethods.Ftp.ListDirectory;
                requestDir.Credentials = new NetworkCredential(FTPUSERID, FTPPASSWORD);
                requestDir.GetResponse();
                MessageBox.Show("Successful to connect to the server","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return true;
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            

        }

        public void DisconnectFTP()
        {
          
        }

        public void CreateXML(string filePath, string fileName, string Xml_out)
        {
        }
    }

}
    
 
    

